package com.example.demo.rabbitMq;

import com.example.demo.utils.date.DateUtils;
import com.example.demo.utils.sql.UUID;
import lombok.AllArgsConstructor;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * RabbitMq 消息生产者
 */
@RestController
@AllArgsConstructor
public class SendMessageController {
    /** 使用RabbitTemplate,这提供了接收/发送等等方法 */
    private RabbitTemplate rabbitTemplate;

    /** 发送消息(直连) */
    @RequestMapping("/send/direct/message")
    public String sendDirectMessage() {

        MessageData data = new MessageData();
        data.setMessageId(UUID.randomUpperUUID(15));
        data.setMessageContent("hello the world");
        data.setCreateTime(DateUtils.now());

        rabbitTemplate.convertAndSend(RabbitMqConstants.DirectExchange, RabbitMqConstants.DirectRoutingKey, data);

        return "OK";
    }

    /** 发送消息(主题) */
    @RequestMapping("/send/topic/message")
    public String sendTopicMessage() {
        MessageData data = new MessageData();
        data.setMessageId(UUID.randomUpperUUID(15));
        data.setMessageContent("hello the world");
        data.setCreateTime(DateUtils.now());

        /** 普通消息发送 */
//        rabbitTemplate.convertAndSend(RabbitMqConstants.TopicExchange, RabbitMqConstants.TopicRoutingKey, data);
        /** 过期进入死信 */
//        rabbitTemplate.convertAndSend(RabbitMqConstants.TopicExchange, RabbitMqConstants.TopicRoutingKey, data, message -> {
//            // 设置消息持久化
//            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
//            // 设置延迟时间
//            message.getMessageProperties().setExpiration("3000");
//            return message;
//        });
        System.out.println("发送时间：" + DateUtils.nowTime());
        return "OK";
    }

    /** 发送延迟消息 */
    @RequestMapping("/send/delayed/message")
    public String sendDelayedMessage() {
        MessageData data = new MessageData();
        data.setMessageId(UUID.randomUpperUUID(15));
        data.setMessageContent("hello the world");
        data.setCreateTime(DateUtils.now());

        /** 延迟消息 rabbitmq 需要安装 rabbitmq_delayed_meaage_exchange插件 */
        rabbitTemplate.convertAndSend(RabbitMqConstants.Delay_Exchange, RabbitMqConstants.Delay_Routing, data, message -> {
            // 设置消息持久化
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            // 设置延迟时间
            message.getMessageProperties().setDelay(3000);
            return message;
        });

        System.out.println("发送时间：" + DateUtils.nowTime());
        return "OK";
    }

}
